<template>
  <view class="relative order-details">
    <nav-bar color="white" bg-color="black" title="会员信息" show-back></nav-bar>

    <view class="flex p-10rpx">
      <view class="flex-1 mx-5rpx bg-white p-20rpx rounded-md flex-col">
        <text class="text-lg font-bold block my-5rpx">基本信息</text>
        <view class="flex-auto">
          <u-tag
            v-if="accountInfo.membershipLevelName"
            :text="accountInfo.membershipLevelName"
            plain
            bg-color="var(--kui-color-theme-light)"
            border-color="var(--kui-color-theme)"
            color="var(--kui-color-theme)"
          />
          <info-panel ref="refInfoPanel" :config="infoConfig" />

          <!-- 操作信息 -->
          <view class="btns-bar-custom">
            <view class="bar-item border-blue-400 border-2 border-solid bg-blue-100" @click="clickEdit">
              <text class="btns-item-txt text-blue-500"> 修改信息 </text>
            </view>
            <view @click="onClickLoseOrCancel" class="bar-item bg-orange-100 border-orange-400 border-2 border-solid">
              <text class="btns-item-txt text-orange-400">
                {{ cardInfo.cardState == 3 ? "解挂卡" : "挂失" }}
              </text>
            </view>
            <view @click="cardReplacement" class="bar-item bg-green-100 border-green-400 border-2 border-solid">
              <text class="btns-item-txt text-green-400"> 补卡 </text>
            </view>
            <view
              class="bar-item bg-red-100 border-red-400 border-2 border-solid"
              :class="{
                'opacity-30': cardInfo.membershipCardType == 2,
              }"
            >
              <text class="btns-item-txt text-red-400" v-if="cardInfo.membershipCardType == 1" @click="accountClosure">
                退卡
              </text>
              <text class="btns-item-txt text-red-400" v-else-if="cardInfo.membershipCardType == 2">
                套餐卡不支持退卡
              </text>
            </view>
            <view class="bar-item border-red-500 border-2 border-solid bg-red-500" @click="accountRemove">
              <text class="btns-item-txt text-white"> 删除老人 </text>
            </view>
          </view>
        </view>
      </view>

      <!-- 账户信息 -->
      <view class="flex flex-col flex-1 mx-5rpx p-20rpx rounded-md bg-white">
        <text class="text-lg font-bold block my-5rpx">账户信息</text>

        <!-- 会员卡 -->
        <view v-if="cardInfo?.membershipCardType == '1'" class="py-5rpx flex-grow">
          <!-- 账户余额 -->
          <view class="flex flex-auto">
            <view class="my-10rpx mr-10rpx">
              <text class="block text-oxl py-10rpx font-bold"> {{ formatMoney(accountDetails?.vaMoney) }} </text>
              <text class="block text-base text-slate-400"> 平台账户余额（元） </text>
            </view>
            <view class="my-10rpx">
              <text class="block text-oxl py-10rpx font-bold"> {{ formatMoney(accountDetails?.businessMoney) }} </text>
              <text class="block text-base text-slate-400"> 商户账户余额（元） </text>
            </view>
          </view>

          <view class="flex flex-auto">
            <view class="my-10rpx mr-10rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ formatMoney(accountDetails?.money) }} </text>
              <text class="block text-base text-slate-400"> 历史账户余额（元） </text>
            </view>
            <view class="my-10rpx mr-10rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ formatMoney(accountInfo?.giveMoney) }} </text>
              <text class="block text-base text-slate-400"> 赠送账户余额（元） </text>
            </view>
            <view class="my-10rpx mr-10rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ accountInfo?.integral || 0 }} </text>
              <text class="block text-base text-slate-400"> 累计积分 </text>
            </view>
          </view>

          <view class="my-10rpx mr-10rpx">
            <text class="block text-xl py-10rpx font-bold"> {{ formatMoney(cardInfo?.deposit) }} </text>
            <text class="block text-base text-slate-400"> 押金（元） </text>
          </view>
        </view>

        <!-- 套餐卡 -->
        <view v-else="cardInfo.membershipCardType == '2'" class="py-5rpx flex-grow">
          <!-- 账户余额 -->
          <view class="flex flex-auto">
            <view class="my-10rpx mr-20rpx">
              <text class="block text-oxl py-10rpx font-bold"> {{ accountInfo?.surplusMealNum }} </text>
              <text class="block text-base text-slate-400"> 套餐卡剩余次数 </text>
            </view>
            <view class="my-10rpx mr-10rpx">
              <text class="block text-xl py-10rpx font-bold" style="line-height: 20rpx">
                {{ formatMoney(cardInfo?.deposit) }}
              </text>
              <text class="block text-base text-slate-400"> 押金 </text>
            </view>
          </view>

          <view class="flex flex-auto">
            <view class="my-10rpx mr-20rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ accountInfo?.packageName || "-" }} </text>
              <text class="block text-base text-slate-400"> 套餐名称 </text>
            </view>
            <view class="my-10rpx mr-20rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ accountInfo?.packageNum || "-" }} </text>
              <text class="block text-base text-slate-400"> 套餐次数 </text>
            </view>
            <view class="my-10rpx mr-10rpx">
              <text class="block text-xl py-10rpx font-bold">
                {{
                  getFieldValueByThisDict("packageType", accountInfo?.packageTypeName, dicts) ||
                  accountInfo?.packageTypeName ||
                  "-"
                }}
              </text>
              <text class="block text-base text-slate-400"> 套餐类型 </text>
            </view>
            <!-- <view class="my-10rpx mr-20rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ accountInfo.accumulationMethodName }} </text>
              <text class="block text-base text-slate-400"> 累计方式 </text>
            </view> -->
          </view>

          <view class="flex flex-auto">
            <view class="my-10rpx mr-20rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ accountInfo.accumulationMethodName || "-" }} </text>
              <text class="block text-base text-slate-400"> 累计方式 </text>
            </view>
            <view class="my-10rpx mr-20rpx">
              <text class="block text-xl py-10rpx font-bold">
                {{ splitStrToArray(accountInfo.mealTypeName).join("/") }}
              </text>
              <text class="block text-base text-slate-400"> 适用餐别 </text>
            </view>
          </view>

          <view class="flex flex-auto">
            <view class="my-10rpx mr-10rpx">
              <text class="block text-xl py-10rpx font-bold"> {{ accountInfo.packageTime || "-" }} </text>
              <text class="block text-base text-slate-400"> 有效时间 </text>
            </view>
          </view>

          <!-- <view class="my-10rpx mr-10rpx">
            <text class="block text-xl py-10rpx font-bold"> {{ formatMoney(cardInfo.deposit) }} </text>
            <text class="block text-base text-slate-400"> 押金 </text>
          </view> -->
        </view>

        <!-- <u-line margin="0.5em 0" /> -->

        <!-- 充值/退款 -->
        <view class="btns-bar-custom flex justify-center">
          <view
            class="btns-item disabled"
            v-if="cardInfo.membershipCardType == 2"
            :style="{ background: 'var(--kui-color-theme)' }"
          >
            <text class="btns-item-txt text-white"> 不支持退款 </text>
          </view>
          <view class="btns-item" v-else @click="clickRefund" :style="{ background: 'var(--kui-color-theme)' }">
            <text class="btns-item-txt text-white"> 退款 </text>
          </view>
          <view class="btns-item confirm" @click="clickRecharge">
            <text class="btns-item-txt"> 充值 </text>
          </view>
          <view class="btns-item" @click="toAccountStatement">
            <text class="btns-item-txt"> 账户流水 </text>
          </view>
        </view>
      </view>
    </view>

    <resultPopup ref="refCommonPopup" :show-icon="false">
      <template #default="{ result }">
        <view
          v-if="result.mode == 'input-loseOrCancel'"
          class="my-30rpx flex-col items-center justify-center text-center w-full"
        >
          <u-textarea
            v-model="loseOrCancelForm.lossRemark"
            placeholder="请输入挂失原因"
            clearable
            count
            custom-style="width: 180rpx;"
          />
        </view>
        <!-- 退卡 -->
        <view
          v-if="result.mode == 'input-accountClosure'"
          class="mb-30rpx flex-col items-center justify-center text-center w-full"
        >
          <text class="font-bold text-red-500 text-oxl">￥{{ formatMoney(calcRefundableAmount(true)) }} </text>

          <view class="relative flex text-center justify-center">
            <text class="text-base py-10rpx text-gray-400"> 退款金额 </text>
            <text class="text-base py-10rpx text-gray-400 ml-5rpx">
              <u-icon name="info-circle-fill" @click="showTips = !showTips"></u-icon>
            </text>
          </view>
          <u-alert
            v-if="showTips"
            title="计算方式"
            type="warning"
            description="退款金额 = 商户账户余额 + 历史账户余额 + 押金"
          ></u-alert>

          <view class="text-base p-10rpx text-red-400">{{ result.content }}</view>
          <u-textarea
            v-model="loseOrCancelForm.cancellationRemark"
            placeholder="请输入注销原因"
            clearable
            count
            custom-style="width: 180rpx;margin: auto;text-align: left;"
          />
        </view>
        <!-- 注销 -->
        <view
          v-if="result.mode == 'input-accountRemove'"
          class="mb-30rpx flex-col items-center justify-center text-center w-full"
        >
          <view class="relative flex mb-5rpx mt-10rpx">
            <view class="flex text-sm flex-1 justify-start">
              <text class="text-slate-500">姓名：</text>
              <text>{{ customerInfo.customerName }}</text>
            </view>
            <view class="flex text-sm flex-1 justify-start">
              <text class="text-slate-500">手机号：</text>
              <text>{{ customerInfo.customerPhone }}</text>
            </view>
          </view>
          <view class="relative flex mb-5rpx">
            <view class="flex text-sm flex-1 justify-start">
              <text class="text-slate-500">会员卡号：</text>
              <text>{{ cardInfo.logicalCardNumber }}</text>
            </view>
            <!-- <view class="flex text-sm flex-1  justify-start">
              <text class="text-slate-500">手机号：</text>
              <text>xxxx</text>
            </view> -->
          </view>

          <u-textarea
            v-model="loseOrCancelForm.cancellationRemark"
            placeholder="请输入删除老人原因"
            clearable
            count
            custom-style="margin: auto;text-align: left;"
          />
          <view class="text-sm p-10rpx text-left text-red-500 font-bold">*{{ result.content }}</view>
          <view class="text-sm text-wrap text-left text-red-400 font-bold"
            >（该功能会进行注销会员卡和注销va卡（若有）以及删除老人）</view
          >
        </view>

        <!-- 退款 -->
        <view
          v-if="result.mode == 'centen-refund'"
          class="my-30rpx flex-col items-center justify-center text-center w-full"
        >
          <text class="block font-bold text-red-500 text-oxl">￥{{ formatMoney(calcRefundableAmount()) }} </text>
          <view class="relative flex text-center justify-center">
            <text class="text-base py-10rpx text-gray-400"> 退款金额 </text>
            <text class="text-base py-10rpx text-gray-400 ml-5rpx">
              <u-icon name="info-circle-fill" @click="showTips = !showTips"></u-icon>
            </text>
          </view>
          <u-alert
            v-if="showTips"
            title="计算方式"
            type="warning"
            description="退款金额 = 商户账户余额 + 历史账户余额"
          ></u-alert>

          <!-- 
           退款不退押金，退卡才退押金
          <text class="block font-bold text-red-500 text-oxl"
            >￥{{ formatMoney(accountInfo.money + cardInfo.deposit) }}
          </text>
          <text class="block text-base py-10rpx text-gray-400">
            退款金额{{ formatMoney(accountInfo.money) }} , 押金 {{ formatMoney(cardInfo.deposit) }}（元）</text
          > -->
        </view>

        <!-- 换卡 -->
        <view
          v-if="result.mode == 'form-cardReplacement'"
          class="box-border pl-5rpx mb-30rpx flex-col items-center justify-center text-center w-full"
        >
          <u-form
            ref="refForm"
            :model="tempForm"
            :rules="tempFormRules"
            label-width="60rpx"
            label-align="left"
            label-position="top"
          >
            <view class="flex">
              <u-form-item label="会员姓名:" prop="customerName" label-position="left" class="flex-1">
                <view class="my-5rpx w-full">
                  <u-text align="left" :text="customerInfo.customerName"></u-text>
                </view>
              </u-form-item>
              <u-form-item label="手机号码:" prop="customerPhone" label-position="left" class="flex-1">
                <view class="my-5rpx w-full">
                  <u-text :text="customerInfo.customerPhone"></u-text>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-between">
              <u-form-item label="物理卡号:" prop="physicalCardNumber" required class="flex-1">
                <view class="w-full mr-20rpx">
                  <u-search
                    :disabled="disabledReadBtn"
                    shape="square"
                    placeholder="读取卡号"
                    v-model="tempForm.physicalCardNumber"
                    search-icon-size="15rpx"
                    action-text="读取"
                    @custom="startReadCard"
                  ></u-search>
                  <!-- <u-input type="digit" v-model="formData.giveMoney" placeholder="请输入金额"></u-input> -->
                </view>
              </u-form-item>
              <u-form-item label="逻辑卡号:" prop="logicalCardNumber" required class="flex-1">
                <view class="w-full">
                  <u-input disabled v-model="tempForm.logicalCardNumber" placeholder="读卡获取已开卡的卡号"></u-input>
                </view>
              </u-form-item>
            </view>

            <view class="">
              <u-form-item label="换卡费用:" prop="cardReplacementFee" required>
                <view class="w-full">
                  <u-input
                    v-model="tempForm.cardReplacementFee"
                    placeholder="请输入押金"
                    type="digit"
                    font-size="10rpx"
                  ></u-input>
                </view>
              </u-form-item>
            </view>
            <view class="">
              <u-form-item label="换卡原因:" prop="remark" required>
                <view class="w-full">
                  <u-textarea v-model="tempForm.remark" placeholder="请输入" auto-height></u-textarea>
                </view>
              </u-form-item>
            </view>
          </u-form>
        </view>
      </template>
      <template #confirm="{ config }">
        <view class="btns-bar">
          <view class="btns-item" @click="refCommonPopup.close('cancel'), (popupLoading = false)">
            <text class="btns-item-txt"> 取消 </text>
          </view>
          <view class="btns-item confirm" :class="{ loading: popupLoading }" @click="popupConfirm(config)">
            <u-loading-icon mode="circle" :show="popupLoading" color="red" />
            <text class="btns-item-txt"> 确定 </text>
          </view>
        </view>
      </template>
    </resultPopup>

    <!-- 通知结果弹窗 -->
    <resultPopup ref="refResultPopup" :show-icon="true"> </resultPopup>

    <nfc-popup ref="refNfcPopup" />
  </view>
</template>
<script lang="ts" setup>
import { onLoad, onShow } from "@dcloudio/uni-app";
import { reactive, ref, onMounted, onBeforeUnmount } from "vue";
import { formatMoney, getFieldValueByThisDict, splitStrToArray } from "@/utils/util";
import resultPopup from "@/components/common-popup/result-popup.vue";
import { getDetailsByCustomerId, getVIPAccountByPhysicalCard } from "./utils";
import {
  changeCard,
  loseOrCancel,
  membershipUpdate,
  rechargeRefund,
  createCardNo,
  membershipRemove,
} from "@/api";
import { useStore } from "vuex";

const showTips = ref(false);

const pageStatus = reactive({
  loading: false,
});

// 页面传递的参数
const pagePam = {
  id: "",
};

// 导入传递的数据
// const globalData: any = inject("$globalData");

const accountInfo = ref({});
const cardInfo = ref({});
const customerInfo = ref({});
// 上一个页面的详细会员信息 （因为 accountInfo 获取到的数据有限， 建议取 accountDetails, 如：customerAccountId）
const accountDetails = ref({});

onLoad((e: any) => {
  console.log("onLoad:>");
  if (e.id) pagePam.id = e.id;
  // if (globalData.pageChannel?.physicalCardNumber) {
  //   console.log("globalData.pageChannel:>", globalData.pageChannel);
  //   // accountDetails.value = { ...globalData.pageChannel };
  // }
});

const getAccountDetailsByPhysicalCard = async (physicalCardNumber: string) => {
  try {
    const info = await getVIPAccountByPhysicalCard(physicalCardNumber);
    // console.log("getAccountDetailsByPhysicalCard:> accountDetails.value", info);
    accountDetails.value = info;
  } catch (error) {
    console.error(error);
  }
};

const getPageData = async (updateAccountInfo = true) => {
  // console.log("getPageData:>", pagePam);
  pageStatus.loading = true;
  try {
    const result = await getDetailsByCustomerId(pagePam.id);
    accountInfo.value = result.accountInfo;
    cardInfo.value = result.cardInfo;
    customerInfo.value = result.customerInfo;
    // 并附加一些会员信息，以便 info-panel 组件使用
    // 从 前一个页面的数据中获取到客户信息
    const vipSubInfo = {
      vipLevel: accountInfo.value.membershipLevelName,
      vipCardNum: cardInfo.value.logicalCardNumber,
      physicalCardNumber: cardInfo.value.physicalCardNumber,
      membershipCardTypeName: cardInfo.value.membershipCardType == 2 ? "套餐办卡" : "普通办卡",
    };
    Object.assign(vipSubInfo, customerInfo.value);
    refInfoPanel.value.updateValues(infoConfig, vipSubInfo, "-");

    // 其他信息处理
    loseOrCancelForm.customerId = customerInfo.value.id;
    loseOrCancelForm.customerInformationId = customerInfo.value.id;
    loseOrCancelForm.membershipCardId = cardInfo.value.membershipCardId;

    if (updateAccountInfo) {
      getAccountDetailsByPhysicalCard(cardInfo.value.physicalCardNumber);
    }
  } catch (error) {
    console.error(error);
  }
};

const refInfoPanel = ref();
// 更新 信息面板组件
const infoConfig = [
  {
    // title: "基本信息",
    children: [
      {
        type: "img",
        key: "faceUrl",
        style: {
          width: "100rpx",
          height: "100rpx",
        },
        border: true,
      },
      {
        type: "txt-double",
        title: ["姓名：", "身份证："],
        value: ["", ""],
        key: ["customerName", "cardId"],
        dict: [],
      },
      {
        type: "txt-double",
        title: ["手机号码：", "年龄："],
        value: ["", ""],
        key: ["customerPhone", "age"],
        dict: [],
      },
      {
        type: "txt-double",
        title: ["客户类型：", "家庭住址："],
        value: ["", ""],
        key: ["customerTypeName", "homeAddress"],
        dict: [],
      },
      {
        type: "txt-double",
        title: ["办卡类型：", "物理卡号："],
        value: ["", ""],
        key: ["membershipCardTypeName", "physicalCardNumber"],
        dict: [],
      },
      {
        type: "txt-double",
        title: ["VA卡：", "会员卡号："],
        value: ["", ""],
        key: ["vaCard", "vipCardNum"],
      },
    ],
  },
];

const refResultPopup = ref();
onMounted(() => {
  getPageData();
});

onShow(() => {
  // 从其他页面返回时，重新获取数据 (? 这里只考虑有数据的情况刷新)
  if (accountDetails.value) {
    // 刷新
    getPageData();
  }
});

onBeforeUnmount(() => {});

// 弹窗
const refCommonPopup = ref();

const store = useStore();

let popupLoading = ref(false);
// 挂失/解挂确认
const popupConfirm = async (config) => {
  if (popupLoading.value === true) return;
  popupLoading.value = true;
  const pam = {
    ...loseOrCancelForm,
  };

  switch (config.mode) {
    // 挂失
    case "input-loseOrCancel":
      pam.cardState = 3;
      try {
        const { data, success, msg } = await loseOrCancel(pam);
        if (!success) throw new Error(msg);
        refResultPopup.value.open({
          title: "成功",
          content: "挂失成功",
          type: "success",
          autoClose: false,
        });
        // 刷新页面
        getPageData();
      } catch (error) {
        console.error(error);
        refResultPopup.value.open({
          title: "失败",
          content: error.data?.msg || "操作失败",
          type: "fail",
          autoClose: false,
        });
        throw error;
      }
      break;
    // 解挂
    case "input-unboxing":
      pam.cardState = 2;
      try {
        const { data, success, msg } = await membershipUpdate(pam);
        if (!success) throw new Error(msg);
        refResultPopup.value.open({
          title: "成功",
          content: "解挂成功",
          type: "success",
          autoClose: false,
        });
        // 刷新页面
        getPageData();
      } catch (error) {
        console.error(error);
        refResultPopup.value.open({
          title: "失败",
          content: error.data?.msg || "操作失败",
          type: "fail",
          autoClose: false,
        });
        throw error;
      }
      break;
    // 退款
    case "centen-refund":
      try {
        const { businessId } = store.getters.businessInfo;

        const { data, success, msg } = await rechargeRefund({
          // customerAccountId: accountDetails.value.customerAccountId,
          customerInformationId: customerInfo.value?.customerInformationId,
          customerName: customerInfo.value?.customerName,
          money: calcRefundableAmount(), // 可退金额合计
          remark: "消费机操作退款",
          refundType: "1", // 退款
          opType: "0", // 余额账户
          businessId: businessId,
        });
        if (!success) throw new Error(msg);
        refResultPopup.value.open({
          title: "成功",
          content: "提交成功",
          type: "success",
          autoClose: false,
        });
        // 刷新页面
        getPageData();
      } catch (error) {
        console.error(error);
        refResultPopup.value.open({
          title: "失败",
          content: error.data?.msg || "操作失败",
          type: "fail",
          autoClose: false,
        });
        throw error;
      }
      break;
    // 退卡
    case "input-accountClosure":
      try {
        const { businessId } = store.getters.businessInfo;
        // 退卡的时候， money是总数， money =历史+平台+押金
        // @2025/01/08 更新 详情见 calcRefundableAmount

        const totalMoney =
          calcRefundableAmount(true); /* accountInfo.money + cardInfo.amountMoney + cardInfo.value?.deposit; */

        const { data, success, msg } = await rechargeRefund({
          // customerAccountId: accountDetails.value.customerAccountId,
          customerInformationId: customerInfo.value?.customerInformationId,
          customerName: customerInfo.value?.customerName,
          deposit: cardInfo.value?.deposit, // 退卡才退押金
          money: totalMoney,
          remark: "消费机操作退卡",
          refundType: "2", // 退卡
          // opType: accountInfo.value.accountType, // 账户类型
          businessId: businessId,
        });
        if (!success) throw new Error(msg);
        refResultPopup.value.open({
          title: "成功",
          content: "提交成功",
          type: "success",
          autoClose: false,
        });
        // 刷新页面
        getPageData();
      } catch (error) {
        console.error(error);
        refResultPopup.value.open({
          title: "失败",
          content: error.data?.msg || "操作失败",
          type: "fail",
          autoClose: false,
        });
        throw error;
      }
      break;

    // 删除老人
    case "input-accountRemove":
      try {
        const postPam = {
          customerInformationId: customerInfo.value.id,
          remark: pam.cancellationRemark,
        };
        const { data, success, msg } = await membershipRemove(postPam);
        if (!success) throw new Error(msg);
        refResultPopup.value.open({
          title: "成功",
          content: "删除老人成功",
          type: "success",
          autoClose: false,
          onClose: () => {
            // 返回上一页
            uni.navigateBack();
          },
        });
      } catch (error) {
        console.error(error);
        refResultPopup.value.open({
          title: "失败",
          content: error.data?.msg || "操作失败",
          type: "fail",
          autoClose: false,
        });
        throw error;
      }
      break;

    // 补卡
    case "form-cardReplacement":
      // 先校验必填
      try {
        await refForm.value.validate();
      } catch (error) {
        popupLoading.value = false;
        return;
      }

      try {
        const { data, success, msg } = await changeCard({
          customerId: customerInfo.value?.customerInformationId,
          logicalCardNumber: tempForm.logicalCardNumber, // 新的逻辑卡号（卡片编号）
          physicalCardNumber: tempForm.physicalCardNumber, // 	新的物理卡号（老人卡号）
          cardId: cardInfo.value?.membershipCardId, // 	会员卡id
          cardReplacementFee: tempForm.cardReplacementFee,
          remark: tempForm.remark, // 换卡原因
          datasource: "3", // 数据来源:1-pc | 2-app | 3-消费机，传3
        });
        if (!success) throw new Error(msg);
        refResultPopup.value.open({
          title: "成功",
          content: "补卡成功",
          type: "success",
          autoClose: false,
        });
        // 刷新页面
        getPageData();
      } catch (error) {
        console.error(error);
        refResultPopup.value.open({
          title: "失败",
          content: error.data?.msg || "操作失败",
          type: "fail",
          autoClose: false,
        });

        // 这里 return 一下，不让关闭弹窗
        popupLoading.value = false;
        return;
      }
      break;

    // 二次确认
    case "confirm-secondary":
      // 需要自己处理，此处只调用方法
      if (config.onConfirm && config.onConfirm instanceof Function) {
        refCommonPopup.value.close();
        popupLoading.value = false;
        return config.onConfirm();
      }
      break;
  }

  refCommonPopup.value.close();
  popupLoading.value = false;
  // info.value.remark = data;
};

/**
 * 计算可退金额
 * @param refundCard // 是否退卡
 */
const calcRefundableAmount = (refundCard = false) => {
  // cooperationMode	合作模式{ 资金专户模式 regulatory /  快速清分模式 fastSettle / 自动分账模式 automatic} @sys_usageMode_jj
  /**
   *               历史余额   商户余额    可退金额合计
   * -----------------------------------------------------
   * 快速清分模式      √          √        历史+商户+押金
   * 资金专户模式      √          ×          历史+押金
   * 自动分账模式      √          ×          历史+押金
   */
  const { usageMode } = store.getters.businessInfo;
  const { money, businessMoney, deposit } = accountDetails.value;
  // console.log("calcRefundableAmount", usageMode, money, businessMoney, deposit);
  switch (usageMode) {
    case "fastSettle":
      return money + businessMoney + (refundCard ? deposit : 0);
    case "regulatory":
    case "automatic":
      return money + (refundCard ? deposit : 0);
    default:
      return money + (refundCard ? deposit : 0);
  }
};

// 暂存提交表单（补卡用）

const refForm = ref();
const tempForm = reactive({
  remark: "",
  cardReplacementFee: 0,
  logicalCardNumber: "",
  physicalCardNumber: "",
});

const tempFormRules = {
  remark: {
    type: "string",
    required: true,
    message: "请输入换卡原因",
    trigger: ["blur", "change"],
  },
  physicalCardNumber: {
    type: "string",
    required: true,
    message: "请获取卡号",
    trigger: ["blur", "change"],
  },
  logicalCardNumber: {
    type: "string",
    required: true,
    message: "请先获取卡号",
    trigger: ["blur", "change"],
  },
};

// 充值
const clickRecharge = () => {
  // console.log("clickRecharge", cardInfo.value?.membershipCardType, accountInfo.value?.surplusMealNum);
  // 判断是否谈餐卡， 如果为套餐卡且有剩余次数，则不能充值
  if (cardInfo.value?.membershipCardType == 2 && accountInfo.value?.surplusMealNum > 0) {
    return refResultPopup.value.open({
      title: "失败",
      content: "套餐卡有剩余次数，不能充值",
      type: "fail",
      autoClose: true,
    });
  } else {
    uni.navigateTo({ url: "./recharge?id=" + accountInfo.value.customerId });
  }
};

// 退款
const clickRefund = () => {
  if (calcRefundableAmount() <= 0)
    return refResultPopup.value.open({
      title: "失败",
      content: "当前账户无可操作的退款余额",
      type: "fail",
      autoClose: false,
    });
  // console.log("clickRefundOrder - 暂无页面");
  refCommonPopup.value.open({
    title: "会员余额退款",
    content: "",
    confirmText: "确认",
    cancelText: "取消",
    autoClose: false,
    //----- 自定义数据
    mode: "centen-refund",
  });
};

// 修改信息
const clickEdit = () => {
  uni.navigateTo({ url: "./edit?id=" + accountInfo.value?.customerId });
};

// 账户流水
const toAccountStatement = () => {
  uni.navigateTo({ url: "./account-statement?id=" + accountInfo.value.customerId });
};

// 挂失 / 解挂
// cardState	发卡状态（1未发卡2已发卡3挂失4注销5已绑定）
const loseOrCancelForm = reactive({
  customerId: "",
  cardState: 3,
  lossRemark: "",
  membershipCardId: "",
  customerInformationId: "",
  cancellationRemark: "",
});

const onClickLoseOrCancel = async () => {
  // 根据发卡状态判断是否可以挂失
  // return console.log("onClickLoseOrCancel:",cardInfo.value?.cardState);
  if (cardInfo.value?.cardState == 5 || cardInfo.value?.cardState == 2) {
    refCommonPopup.value.open({
      title: "会员卡挂失",
      content: "",
      confirmText: "确认",
      cancelText: "取消",
      autoClose: false,
      //----- 自定义数据
      mode: "input-loseOrCancel",
    });
  } else {
    refCommonPopup.value.open({
      title: "会员卡解挂失",
      content: "是否进行当前会员卡解挂操作？",
      confirmText: "确认",
      cancelText: "取消",
      autoClose: false,
      //----- 自定义数据
      mode: "input-unboxing",
    });
  }
};

// 退卡
const accountClosure = async () => {
  refCommonPopup.value.open({
    title: "会员卡退卡",
    content: "该操作无法撤销，请确认是否继续退卡？",
    confirmText: "确认",
    cancelText: "取消",
    autoClose: false,
    //----- 自定义数据
    mode: "input-accountClosure",
  });
};

// 删除老人
const accountRemove = async () => {
  // 判断当前用户是否有余额(历史。商户。平台, 押金)， 有余额则提示
  if (
    accountDetails.value?.money > 0 ||
    accountDetails.value?.businessMoney > 0 ||
    accountDetails.value?.vaMoney > 0 ||
    cardInfo.value?.deposit > 0
  ) {
    return refResultPopup.value.open({
      title: "删除老人失败",
      content: "当前账户仍有余额， 无法进行删除老人",
      type: "fail",
      // showIcon: false,
      autoClose: false,
    });
  } else {
    refCommonPopup.value.open({
      title: "确认删除",
      content: "删除老人后将无法再使用，是否继续？",
      confirmText: "确认",
      cancelText: "取消",
      autoClose: false,
      //----- 自定义数据
      mode: "confirm-secondary",
      onConfirm: () => {
        // 组合需要显示的数据
        const vipSubInfo = {
          vipLevel: accountInfo.value.membershipLevelName,
          vipCardNum: cardInfo.value.logicalCardNumber,
          physicalCardNumber: cardInfo.value.physicalCardNumber,
          membershipCardTypeName: cardInfo.value.membershipCardType == 2 ? "套餐办卡" : "普通办卡",
        };
        Object.assign(vipSubInfo, customerInfo.value);

        refCommonPopup.value.open({
          title: "删除老人",
          content: "该操作无法撤销，继续删除老人请填入删除原因。",
          confirmText: "确认",
          cancelText: "取消",
          autoClose: false,
          //----- 自定义数据
          mode: "input-accountRemove",
          // 删除老人面板上显示的信息
          infoConfig: infoConfig,
          info: vipSubInfo,
        });
      },
    });
  }
};

// 补卡
const cardReplacement = () => {
  // 如果当前卡未挂失， 无法补卡换卡
  if (cardInfo.value?.cardState != 3) {
    return refResultPopup.value.open({
      title: "提示信息",
      content: "当前会员卡未挂失，无法进行补卡/换卡操作",
      type: "info",
      autoClose: false,
    });
  } else {
    refCommonPopup.value.open({
      title: "会员卡补卡",
      content: "",
      confirmText: "确认",
      cancelText: "取消",
      autoClose: false,
      //----- 自定义数据
      mode: "form-cardReplacement",
    });
  }
};

// 读卡
const disabledReadBtn = ref(false);
const refNfcPopup = ref();
const startReadCard = async () => {
  if (disabledReadBtn.value) return uni.showToast({ title: "正在读卡中", icon: "none" });
  console.log("开始读卡");
  disabledReadBtn.value = true;
  try {
    const card = await refNfcPopup.value.reading();
    console.log("读卡结束", card);
    if (card) {
      tempForm.physicalCardNumber = card;
      // 获取当前卡的对应的逻辑卡号
      refreshCardNumber();
    }
    disabledReadBtn.value = false;
  } catch (error) {
    console.error("读卡失败", error);
    uni.showToast({ title: "读卡失败", icon: "none" });
    disabledReadBtn.value = false;
  }
};

// 刷新逻辑卡号
const refreshCardNumber = async () => {
  console.log("刷新逻辑卡号");
  disabledReadBtn.value = true;
  try {
    const pam = {
      physicalCardNumber: tempForm.physicalCardNumber,
      autoCard: 2,
    };
    const { data, success } = await createCardNo(pam);
    if (success && data) {
      tempForm.logicalCardNumber = data;
      console.log("刷新逻辑卡号成功", tempForm);
      refResultPopup.value.open({
        title: "提示信息",
        content: "逻辑卡号获取成功",
        type: "success",
      });
    }
    disabledReadBtn.value = false;
  } catch (error) {
    console.error("刷新逻辑卡号失败", error);
    disabledReadBtn.value = false;
    refResultPopup.value.open({
      title: "提示",
      content: error.message || "刷新逻辑卡号失败",
      type: "fail",
    });
  }
};

// 其他自定义字典
const dicts = reactive({
  packageType: [
    {
      dictLabel: "日套餐",
      dictValue: "day",
    },
    {
      dictLabel: "月套餐",
      dictValue: "month",
    },
  ],
  mealType: [
    {
      dictLabel: "早餐",
      dictValue: 1,
    },
    {
      dictLabel: "午餐",
      dictValue: 2,
    },
    {
      dictLabel: "晚餐",
      dictValue: 3,
    },
  ],
  accumulationMethod: [
    {
      dictLabel: "全部清零",
      dictValue: 1,
    },
    {
      dictLabel: "全部累计",
      dictValue: 2,
    },
    {
      dictLabel: "部分累计",
      dictValue: 3,
    },
  ],
});
</script>
<style lang="scss" scoped>
.order-details {
  // height: 90vh;
  box-sizing: border-box;

  .food-list {
    width: 100%;
    min-width: none !important;
  }

  ::v-deep .uni-table {
    min-width: auto !important;
  }

  .details-text {
    font-size: 10rpx;
    white-space: nowrap;
    overflow: scroll;

    &.d-name {
      color: rgb(179, 179, 179);
    }

    &.d-price {
      color: red;
      font-weight: bold;
    }

    &.d-price-back {
      color: rgb(14, 187, 52);
      font-weight: bold;
    }

    &.d-price-discount {
      color: orange;
      font-weight: bold;
    }
  }
}

.btns-bar-custom {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .bar-item {
    font-size: 8rpx;
    padding: 5rpx 10rpx;
    border-radius: 3rpx;
  }

  .btns-item {
    background-color: #efefef;
    padding: 5rpx 12rpx;
    border-radius: 5rpx;
    font-size: 12rpx;
    margin: 0 5rpx;
    display: flex;
    align-items: center;

    &.confirm {
      color: white;
      background-color: red;
    }

    .btns-item-txt {
      font-size: 10rpx;
      padding: 5rpx 15rpx;
      width: fit-content;

      &.disabled {
        opacity: 0.5;
      }
    }

    ::v-deep .u-button {
      padding: 2rpx 20rpx;
    }
  }
}

/** 这是弹窗按钮的样式 */
@import "@/components/common-popup/btns.scss";
</style>
